// Data factory functions for creating default objects

import type { 
  User, 
  Message, 
  Chat, 
  ClientData, 
  Tag, 
  ChatHistory, 
  ClientPreferences,
  MessageMetadata 
} from './index'
import { generateId } from '@/utils'

// User factory
export function createUser(overrides: Partial<User> = {}): User {
  const now = new Date()
  return {
    id: generateId(),
    name: '',
    avatar: '/default-avatar.png',
    role: 'client',
    status: 'offline',
    lastSeen: now,
    createdAt: now,
    updatedAt: now,
    ...overrides
  }
}

// Message factory
export function createMessage(overrides: Partial<Message> = {}): Message {
  const now = new Date()
  return {
    id: generateId(),
    chatId: '',
    senderId: '',
    content: '',
    timestamp: now,
    type: 'text',
    status: 'sending',
    edited: false,
    createdAt: now,
    updatedAt: now,
    ...overrides
  }
}

// Chat factory
export function createChat(overrides: Partial<Chat> = {}): Chat {
  const now = new Date()
  return {
    id: generateId(),
    participants: [],
    lastMessage: null,
    unreadCount: 0,
    status: 'pending',
    tags: [],
    priority: 'normal',
    createdAt: now,
    updatedAt: now,
    ...overrides
  }
}

// Client data factory
export function createClientData(overrides: Partial<ClientData> = {}): ClientData {
  const now = new Date()
  return {
    id: generateId(),
    name: '',
    avatar: '/default-avatar.png',
    language: 'zh-CN',
    tags: [],
    notes: '',
    customFields: {},
    history: [],
    preferences: createClientPreferences(),
    createdAt: now,
    updatedAt: now,
    ...overrides
  }
}

// Client preferences factory
export function createClientPreferences(overrides: Partial<ClientPreferences> = {}): ClientPreferences {
  return {
    preferredLanguage: 'zh-CN',
    communicationChannel: 'chat',
    availableHours: {
      start: '09:00',
      end: '18:00',
      timezone: 'Asia/Shanghai'
    },
    notifications: true,
    ...overrides
  }
}

// Tag factory
export function createTag(overrides: Partial<Tag> = {}): Tag {
  return {
    id: generateId(),
    name: '',
    color: '#3b82f6',
    ...overrides
  }
}

// Chat history factory
export function createChatHistory(overrides: Partial<ChatHistory> = {}): ChatHistory {
  return {
    id: generateId(),
    date: new Date(),
    summary: '',
    messages: [],
    ...overrides
  }
}

// Message metadata factory
export function createMessageMetadata(overrides: Partial<MessageMetadata> = {}): MessageMetadata {
  return {
    ...overrides
  }
}

// Batch creation functions
export function createUsers(count: number, overrides: Partial<User> = {}): User[] {
  return Array.from({ length: count }, (_, index) => 
    createUser({ 
      ...overrides, 
      name: overrides.name || `User ${index + 1}` 
    })
  )
}

export function createMessages(count: number, chatId: string, senderId: string, overrides: Partial<Message> = {}): Message[] {
  return Array.from({ length: count }, (_, index) => 
    createMessage({ 
      ...overrides, 
      chatId,
      senderId,
      content: overrides.content || `Message ${index + 1}`,
      timestamp: new Date(Date.now() - (count - index) * 60000) // 1 minute intervals
    })
  )
}

export function createChats(count: number, overrides: Partial<Chat> = {}): Chat[] {
  return Array.from({ length: count }, (_, index) => 
    createChat({ 
      ...overrides, 
      title: overrides.title || `Chat ${index + 1}` 
    })
  )
}

export function createTags(names: string[], color: string = '#3b82f6'): Tag[] {
  return names.map(name => createTag({ name, color }))
}

// Mock data generators for development
export function generateMockUser(role: 'agent' | 'client' = 'client'): User {
  const names = role === 'agent' 
    ? ['张小明', '李小红', '王小华', '刘小强', '陈小美']
    : ['客户A', '客户B', '客户C', '客户D', '客户E']
  
  const name = names[Math.floor(Math.random() * names.length)]
  const statuses: Array<'online' | 'offline' | 'away'> = ['online', 'offline', 'away']
  const status = statuses[Math.floor(Math.random() * statuses.length)]
  
  return createUser({
    name,
    role,
    status,
    email: role === 'client' ? `${name.toLowerCase()}@example.com` : undefined,
    phone: role === 'client' ? `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}` : undefined
  })
}

export function generateMockMessage(chatId: string, senderId: string, type: 'text' | 'image' | 'file' = 'text'): Message {
  const textMessages = [
    '你好，我需要帮助',
    '请问这个问题怎么解决？',
    '谢谢你的帮助',
    '我明白了',
    '还有其他问题吗？'
  ]
  
  let content = ''
  let metadata: MessageMetadata | undefined
  
  switch (type) {
    case 'text':
      content = textMessages[Math.floor(Math.random() * textMessages.length)]
      break
    case 'image':
      content = '发送了一张图片'
      metadata = {
        fileName: 'image.jpg',
        fileSize: Math.floor(Math.random() * 1000000) + 100000,
        fileType: 'image/jpeg',
        imageWidth: 800,
        imageHeight: 600
      }
      break
    case 'file':
      content = '发送了一个文件'
      metadata = {
        fileName: 'document.pdf',
        fileSize: Math.floor(Math.random() * 5000000) + 500000,
        fileType: 'application/pdf'
      }
      break
  }
  
  return createMessage({
    chatId,
    senderId,
    content,
    type,
    metadata,
    status: 'read'
  })
}

export function generateMockChat(participants: User[]): Chat {
  const priorities: Array<'low' | 'normal' | 'high' | 'urgent'> = ['low', 'normal', 'high', 'urgent']
  const statuses: Array<'active' | 'closed' | 'pending' | 'archived'> = ['active', 'closed', 'pending']
  
  const chat = createChat({
    participants,
    priority: priorities[Math.floor(Math.random() * priorities.length)],
    status: statuses[Math.floor(Math.random() * statuses.length)],
    unreadCount: Math.floor(Math.random() * 10),
    tags: ['客服', '技术支持'].slice(0, Math.floor(Math.random() * 3))
  })
  
  // Generate a last message
  if (participants.length > 0) {
    const randomSender = participants[Math.floor(Math.random() * participants.length)]
    chat.lastMessage = generateMockMessage(chat.id, randomSender.id)
  }
  
  return chat
}

export function generateMockClientData(): ClientData {
  const companies = ['阿里巴巴', '腾讯', '百度', '字节跳动', '美团']
  const positions = ['产品经理', '技术总监', '市场专员', '销售经理', '客户经理']
  const locations = ['北京', '上海', '深圳', '杭州', '广州']
  
  return createClientData({
    name: `客户${Math.floor(Math.random() * 1000)}`,
    email: `client${Math.floor(Math.random() * 1000)}@example.com`,
    phone: `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
    company: companies[Math.floor(Math.random() * companies.length)],
    position: positions[Math.floor(Math.random() * positions.length)],
    location: locations[Math.floor(Math.random() * locations.length)],
    tags: createTags(['VIP客户', '重要客户', '新客户'].slice(0, Math.floor(Math.random() * 3) + 1)),
    notes: '这是一个重要的客户，需要特别关注。'
  })
}